package com.func.boom.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.func.boom.constant.Common;
import com.func.boom.dao.dto.RegisterDto;
import com.func.boom.dao.mapper.UserMapper;
import com.func.boom.entity.TSysUser;
import com.func.boom.enums.ResultEnums;
import com.func.boom.service.UserService;
import com.func.boom.utils.CommonUtil;
import com.func.boom.utils.ResultEntity;
import com.func.boom.utils.RsaEncrypt;
import com.func.boom.utils.jwt.Authentication;
import com.func.boom.utils.jwt.JwtHelper;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Yulei
 * @date 2020-09-10 15:24:08
 * @desc
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, TSysUser> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private Producer captchaProducer;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private HttpServletRequest request;


    @Override
    public ResultEntity<?> login(Authentication authentication) {
        try {
            //根据手机号查询用户信息
            TSysUser userParam = new TSysUser();
            userParam.setPhone(authentication.getPhone());
            List<TSysUser> TSysUserList = userMapper.selectUserList(userParam);
            if(TSysUserList.size() == 0){
                return ResultEntity.error(ResultEnums.ERROR_20300);
            }
            TSysUser tSysUser = TSysUserList.get(0);
                    //对比密码是否正确
            String password = RsaEncrypt.decrypt(authentication.getPassword());
            String inputPassword = CommonUtil.md5(password);
            if(!StrUtil.equals(inputPassword, tSysUser.getPassword())){
                return ResultEntity.error(ResultEnums.ERROR_20200);
            }

            String token = JwtHelper.generateJWT(StrUtil.str(tSysUser.getId(), CharsetUtil.UTF_8), tSysUser.getPhone());
            Map result = CollectionUtil.newHashMap();
            result.put("phone", authentication.getPhone());
            result.put("token", token);
            return ResultEntity.success(result);
        } catch (Exception e) {
            log.error("登录异常: {}", e.getMessage());
        }

        return ResultEntity.error();
    }

    @Override
    public ResultEntity<?> register(RegisterDto user) {
        try {
            //比对验证码
            String key = Common.REGISTER_CAPTCHA_KEY + "-" + CommonUtil.getIpAddr(request);
            String captcha = StrUtil.str(redisTemplate.opsForValue().get(key), CharsetUtil.UTF_8).toLowerCase();
            String inputCap = StrUtil.str(user.getCaptcha(), CharsetUtil.UTF_8).toLowerCase();
            if(!StrUtil.equals(captcha, inputCap)){
                return ResultEntity.error(ResultEnums.ERROR_20400);
            }

            //查询手机号是否已经注册
            Map<String, Object> map = new HashMap<String, Object>(){{
                put("phone", user.getPhone());
            }};
            TSysUser userParam = new TSysUser();
            userParam.setPhone(user.getPhone());
            List<TSysUser> userList = userMapper.selectUserList(userParam);
            if(userList.size() != 0){
                return ResultEntity.error(ResultEnums.ERROR_20100);
            }

            //将密码md5
            String password = RsaEncrypt.decrypt(user.getPassword());
            user.setPassword(CommonUtil.md5(password));

            int insert = userMapper.insertUser(user);
            if(insert == 1){
                return ResultEntity.success(ResultEnums.SUCCESS_SAVE);
            }
        } catch (Exception e) {
            log.error("注册异常: {}", e.getMessage());
        }
        return ResultEntity.error();
    }

    @Override
    public void getCaptcha(HttpServletResponse response, String phone, Integer type) {
        // 生成验证码
        String text = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(text);
        //即将生成的验证码内容存到redis中
        String key = "";
        if(type == 0){
            key = Common.REGISTER_CAPTCHA_KEY + "-" + CommonUtil.getIpAddr(request);
        }
        redisTemplate.opsForValue().set(key, text);
        redisTemplate.expire(key, Common.CAPTCHA_EXPIRE_TIME, TimeUnit.SECONDS);
        // 将突图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            log.error("响应验证码失败: {}", e.getMessage());
        }
    }

    @Override
    public List<TSysUser> getUserList(TSysUser TSysUser) {
        return userMapper.selectUserList(TSysUser);
    }

}
